import util from '../../utils/util.js'
const app = getApp()
Page({
  data: {
    posts: [],
    user: null,
    lover: null
  },
  gotoPost(e) {
    wx.navigateTo({
      url: '/pages/community/post/post?postid=' + e.currentTarget.dataset.postid,
    })
  },
  addPost() {
    if (app.globalData.islogin == false) {
      wx.showToast({
        icon: 'none',
        title: '请先登陆哦',
      })
    } else {
      wx.navigateTo({
        url: '/pages/community/addpost/addpost',
      })
    }
  },
  onPullDownRefresh() {
    // this.setData({
    //   posts: []
    // })
    this.getPost(0)
  },
  onReachBottom() {
    this.getPost(this.data.posts.length)
  },
  getPost(skiplength) {
    wx.showLoading({
      title: '加载中'
    })
    wx.cloud.callFunction({
      name: 'getPosts',
      data: {
        skiplength: skiplength
      }
    })
      .then(res => {
        if (res.result.list.length <= 0) {
          wx.showToast({
            icon: 'none',
            title: '没有更多数据啦',
          })
          return;
        }
        wx.stopPullDownRefresh()
        if (skiplength == 0) {  // 重头刷新
          this.setData({
            posts: res.result.list,
            user: wx.getStorageSync('user'),
            lover: wx.getStorageSync('lover')
          })
        } else {         // 分页加载
          this.setData({
            posts: this.data.posts.concat(res.result.list),
            user: wx.getStorageSync('user'),
            lover: wx.getStorageSync('lover')
          })
        }
        wx.hideLoading()
      })
      .catch(res => {
        console.log("请求失败", res)
      })
  },
  onLoad(){
    this.getPost(0)
  },
})